package web;

import java.util.List;

import model.Algo;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

import persistencia.Persistencia;

public class HiberSpring extends AbstractPage{
	private static final long serialVersionUID = 1L;
	private Algo algo;
	protected Component lista;
	@SpringBean(name="persistencia")
	private Persistencia persistencia;

	public HiberSpring() {
		super();
		this.algo = new Algo();
		this.add(new Form<Void>("form").add(
			algo_nuevo(),
			algo_guardar(),
			lista = algos()
		));
	}

	private Component algos() {
		IModel<List<Algo>> source = new AbstractReadOnlyModel<List<Algo>>(){
			private static final long serialVersionUID = 1L;

			@Override
			public List<Algo> getObject() {
				return persistencia.buscarAlgos();
			}
		};
		return new ListView<Algo>("algos", source){
			private static final long serialVersionUID = 1L;

			@Override
			protected void populateItem(ListItem<Algo> item) {
				Algo algo = item.getModelObject();
				
				item.add(
					new Label("algos_algo", algo.getAlgo())
				);
			}
		};
	}

	private Component algo_guardar() {
		return new AjaxButton("algo_guardar") {
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				persistencia.guardar(algo);
				algo = new Algo();
				target.add(HiberSpring.this);
			}
			
			@Override
			protected void onError(AjaxRequestTarget target, Form<?> form) {
				refrescarFeedback(target);
			}
		};
	}

	private Component algo_nuevo() {
		IModel<String> model = new PropertyModel<String>(this, "algo.algo");
		return new TextField<String>("algo_nuevo", model);
	}

	//getters&setters
	public void setAlgo(Algo algo) {
		this.algo = algo;
	}
	public Algo getAlgo() {
		return algo;
	}
}